package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.entities.*;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.ActivityAddressService;
import cn.dakaqi.services.ActivityService;
import cn.dakaqi.services.ActivityTagService;
import cn.dakaqi.services.SysActivityTagService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.alibaba.fastjson.JSON;
import com.mangofactory.swagger.annotations.ApiIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springside.modules.web.MediaTypes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/5/9.
 */
@Controller
@RequestMapping(value = "/activity")
@Slf4j
@ApiIgnore
public class ActivityController extends BaseController
{
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    SysActivityTagService sysActivityTagService;
    @Autowired
    ActivityTagService activityTagService;
    @Autowired
    ActivityAddressService activityAddressService;
    @Autowired
    ConfigUtil configUtil;


    @Override
    protected ModelAndView initModelAndView(String groupCode,String view,HttpServletRequest request)
    {
        ModelMap modelMap = super.initData(groupCode,request);
        modelAndView = new ModelAndView(view,modelMap);

        //系统活动标签
        List<SysActivityTag> tags =  this.sysActivityTagService.findAll();
        modelAndView.addObject("tags",tags);
        return modelAndView;
    }
    @Override
    protected void clearModelAndView(String groupCode,HttpServletRequest request)
    {

    }
    private Group getCurGroup(HttpServletRequest request)
    {
        return ((Group)request.getSession().getAttribute("curGroup"));
    }
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView list(
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
            @RequestParam(value = "sortType", defaultValue = "auto") String sortType,
            @RequestParam(value = "status", defaultValue = "2") int status, HttpServletRequest request)
    {
        String view = "activity/index";
        Group group = getCurGroup(request);
        String key = group.getGroupCode()+"/"+view;
        modelAndView = initModelAndView(group.getGroupCode(), view,request);
        //查询当前社团的所有活动
        Page<Activity> data = this.activityService.findByGroupCode(group.getGroupCode(),pageNumber);
        modelAndView.addObject("data", data);
        return modelAndView;
    }
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("startDate") String startDate,@RequestParam("endDate") String endDate,@RequestParam("title") String title,HttpServletRequest request)
    {
        String view = "activity/index";
        Group group = getCurGroup(request);
        modelAndView = initModelAndView(group.getGroupCode(), view,request);
        Page<Activity> data = this.activityService.searchActivity(group.getGroupCode(),title,startDate,endDate,1);
        modelAndView.addObject("data", data);
        return modelAndView;
    }
    @RequestMapping(value = "/pubSingle", method = RequestMethod.GET)
    public ModelAndView pubSingle(HttpServletRequest request)
    {
        String view = "activity/singleForm";
        Group group = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(group.getGroupCode(), view, request);
        modelAndView.addObject("activity", new Activity());
        modelAndView.addObject("action", "/pubSingle");
        //查询当前用户的10个常用地址
        Volunteer volunteer = (Volunteer)request.getSession().getAttribute("volunteer");
        if(null != volunteer)
        {
            try
            {
                Page<ActivityAddress> data = this.activityAddressService.findByMemberCode(volunteer.getMemberCode(), "",ConfigUtil.getClientId(), 1);
                modelAndView.addObject("addresses", data);
                //查询当前用户自定义的标签
                Page<ActivityTag> tags = this.activityTagService.findByMemberCode(volunteer.getMemberCode(),"",1);
                modelAndView.addObject("mytags", tags);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        //查询系统活动标签
        List<SysActivityTag> systags = this.sysActivityTagService.findAll();
        modelAndView.addObject("systags", systags);


        return modelAndView;
    }

    @RequestMapping(value = "/pubSingle", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> pubSingle(@RequestParam("name") String  name,
                                       @RequestParam("demo") String demo,
                                       @RequestParam("startTime") String startTime,
                                       @RequestParam("endTime") String endTime,
                                       @RequestParam("tags") String tags,
                                       @RequestParam("mytags") String mytags,
                                       @RequestParam("needs") String needs,
                                       @RequestParam("scope") String scope,
                                       @RequestParam("addressId") String addressId,
                                       @RequestParam("myprovince") String myprovince,
                                       @RequestParam("mycity") String mycity,
                                       @RequestParam("mydistrict") String mydistrict,
                                       @RequestParam("myaddress") String myaddress,
                                       @RequestParam("myaddressname") String myaddressname,
                                       @RequestParam("myLng") String myLng,
                                       @RequestParam("myLat") String myLat,
                                       @RequestParam("monitorId") String monitorId,
                                       @RequestParam("skills") String skills,
                                       @RequestParam("activityCode") String activityCode,
                                       HttpServletRequest request)
    {

        JsonResult jsonResult = new JsonResult();
        String message = "发布成功";

        if(StringUtils.isBlank(activityCode))
        {
            try
            {
                saveNewActivity( name,demo,startTime,endTime,tags,mytags,needs,scope,addressId,myprovince,mycity,mydistrict,myaddress,myaddressname,myLng,myLat,monitorId,skills,activityCode,request);
                jsonResult.setCode(JsonResult.CODE_SUCCESS);
                jsonResult.setMessage(message);
            } catch (ServiceRuntimeException e)
            {
                e.printStackTrace();
                message = e.getMessage();
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage(message);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                message = "发布失败";
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage(message);
            }
        }
        else
        {
            try
            {
                updateActivity(name,demo,startTime,endTime,tags,mytags,needs,scope,addressId,myprovince,mycity,mydistrict,myaddress,myaddressname,myLng,myLat,monitorId,skills,activityCode,request);
                jsonResult.setCode(JsonResult.CODE_SUCCESS);
                jsonResult.setMessage(message);
            } catch (ServiceRuntimeException e)
            {
                e.printStackTrace();
                message = e.getMessage();
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage(message);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                message = "发布失败";
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage(message);
            }
        }
        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    private void updateActivity(String name,
                                String demo,
                                String startTime,
                                String endTime,
                                String tags,
                                String mytags,
                                String needs,
                                String scope,
                                String addressId,
                                String myprovince,
                                String mycity,
                                String mydistrict,
                                String myaddress,
                                String myaddressname,
                                String myLng,
                                String myLat,
                                String monitorId,
                                String skills,
                                String activityCode,
                                HttpServletRequest request)
    {
        Activity activity = this.activityService.findByActivityCode(activityCode);
        activity.setSkill(skills);
        Volunteer curVolunteer = (Volunteer)request.getSession().getAttribute("volunteer");
        Group group = getCurGroup(request);
        //如果tags 为空则是用户自定义标签，此时需要保存用户标签
        if(StringUtils.isBlank(tags))
        {
            saveActivityTag(curVolunteer, mytags);
            activity.setTags(mytags);
        }
        else
            activity.setTags(tags);

        //如果addressId =0 则是用户添加了新的活动地点，此时需要保存新的活动地点
        if(Long.parseLong(addressId) ==0L)
        {
            activity.setProvince(myprovince);
            activity.setCity(mycity);
            activity.setDistrict(mydistrict);
            activity.setAddress(myprovince+mycity+mydistrict+myaddress);
            activity.setLat(Double.parseDouble(myLat));
            activity.setLng(Double.parseDouble(myLng));
            saveActivityAddress(curVolunteer, myprovince, mycity, mydistrict, myaddress, myaddressname, myLng, myLat);
        }
        else
        {
            ActivityAddress address = this.activityAddressService.findOne(Long.parseLong(addressId));
            activity.setProvince(address.getProvince());
            activity.setCity(address.getCity());
            activity.setDistrict(address.getDistrict());
            activity.setAddress(address.getAddress());
            activity.setLat(address.getLat());
            activity.setLng(address.getLng());
        }
        activity.setWeekDay("1");
        activity.setGroup(group);
        activity.setCreateUser(curVolunteer);
        activity.setMonitor(new Volunteer(Long.parseLong(monitorId)));
        activity.setName(name);
        activity.setDemo(demo);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setTags(tags);
        activity.setNeeds(Integer.parseInt(needs));
        activity.setScope(Integer.parseInt(scope));
        this.activityService.update(activity);
    }

    private void saveNewActivity(String  name,
                                 String demo,
                                 String startTime,
                                 String endTime,
                                 String tags,
                                 String mytags,
                                 String needs,
                                 String scope,
                                 String addressId,
                                 String myprovince,
                                 String mycity,
                                 String mydistrict,
                                 String myaddress,
                                 String myaddressname,
                                 String myLng,
                                 String myLat,
                                 String monitorId,
                                 String skills,
                                 String activityCode,
                                 HttpServletRequest request)
    {
        Activity activity = new Activity();
        activity.setSkill(skills);
        Volunteer curVolunteer = (Volunteer)request.getSession().getAttribute("volunteer");
        Group group = getCurGroup(request);
        //如果tags 为空则是用户自定义标签，此时需要保存用户标签
        if(StringUtils.isBlank(tags))
        {
            saveActivityTag(curVolunteer, mytags);
            activity.setTags(mytags);
        }
        else
            activity.setTags(tags);

        //如果addressId =0 则是用户添加了新的活动地点，此时需要保存新的活动地点
        if(Long.parseLong(addressId) ==0L)
        {
            activity.setProvince(myprovince);
            activity.setCity(mycity);
            activity.setDistrict(mydistrict);
            activity.setAddress(myprovince+mycity+mydistrict+myaddress);
            activity.setLat(Double.parseDouble(myLat));
            activity.setLng(Double.parseDouble(myLng));
            saveActivityAddress(curVolunteer, myprovince, mycity, mydistrict, myaddress, myaddressname, myLng, myLat);
        }
        else
        {
            ActivityAddress address = this.activityAddressService.findOne(Long.parseLong(addressId));
            activity.setProvince(address.getProvince());
            activity.setCity(address.getCity());
            activity.setDistrict(address.getDistrict());
            activity.setAddress(address.getAddress());
            activity.setLat(address.getLat());
            activity.setLng(address.getLng());
        }
        activity.setClient(ConfigUtil.getClientId());
        activity.setWeekDay("1");
        activity.setGroup(group);
        activity.setCreateUser(curVolunteer);
        Volunteer temp = this.volunteerService.findOne(Long.parseLong(monitorId));
        activity.setMonitor(temp);
        activity.setName(name);
        activity.setDemo(demo);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setTags(tags);
        activity.setNeeds(Integer.parseInt(needs));
        activity.setScope(Integer.parseInt(scope));
        this.activityService.save(activity);
    }

    @RequestMapping(value = "/update/{activityCode}", method = RequestMethod.GET)
    public ModelAndView update(@PathVariable("activityCode") String activityCode,HttpServletRequest request)
    {
        String view = "activity/singleForm";
        Group group = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(group.getGroupCode(), view, request);
        modelAndView.addObject("activity", this.activityService.findByActivityCode(activityCode));
        modelAndView.addObject("action", "/update");
        //查询当前用户的10个常用地址
        Volunteer volunteer = (Volunteer)request.getSession().getAttribute("volunteer");
        if(null != volunteer)
        {
            try
            {
                Page<ActivityAddress> data = this.activityAddressService.findByMemberCode(volunteer.getMemberCode(), "",ConfigUtil.getClientId(), 1);
                modelAndView.addObject("addresses", data);
                //查询当前用户自定义的标签
                Page<ActivityTag> tags = this.activityTagService.findByMemberCode(volunteer.getMemberCode(),"",1);
                modelAndView.addObject("mytags", tags);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        //查询系统活动标签
        List<SysActivityTag> systags = this.sysActivityTagService.findAll();
        modelAndView.addObject("systags", systags);
        return modelAndView;
    }

    private void saveActivityAddress(Volunteer curVolunteer, String myprovince,String mycity,String mydistrict,String myaddress,String myaddressname,String myLng,String myLat)
    {
        Map<String,String> map = new HashMap<String,String >();
        map.put("memberCode",curVolunteer.getMemberCode());
        map.put("address",myaddress);
        map.put("name",myaddressname);
        map.put("province",myprovince);
        map.put("city",mycity);
        map.put("district",mydistrict);
        map.put("lng",myLng);
        map.put("lat",myLat);
        this.activityAddressService.save(JSON.toJSONString(map));
    }

    private void saveActivityTag(Volunteer curVolunteer, String mytags)
    {
        Map<String,String> map = new HashMap<String,String >();
        map.put("memberCode",curVolunteer.getMemberCode());
        map.put("name",mytags);
        activityTagService.save(JSON.toJSONString(map));
    }

    @RequestMapping(value = "/detail/{activityCode}",method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("activityCode") String activityCode,HttpServletRequest request)
    {
        String view = "activity/detail";
        Group group = getCurGroup(request);
        modelAndView = initModelAndView(group.getGroupCode(), view,request);
        Activity activity= this.activityService.findByActivityCode(activityCode);
        modelAndView.addObject("activity", activity);
        return modelAndView;
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> delete(@RequestParam("activityCode") String activityCode,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String  message;
        try
        {
            volunteer = (Volunteer)request.getSession().getAttribute("volunteer");
            this.activityService.delete(volunteer.getMemberCode(),activityCode,"");
            message =  "活动取消成功";
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message =  e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            message =  e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
        }
        jsonResult.setMessage(message);
        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

}
